//
//  HMComposeViewController.swift
//  MicroBlog
//
//  Created by QT on 15/8/5.
//  Copyright © 2015年 綦敦涛. All rights reserved.
//

import UIKit

class HMComposeViewController: UIViewController {

    // 懒加载键盘输入视图
    private lazy var emoticonVC: EmoticonViewController = EmoticonViewController {[weak self] (emoticon) -> () in
        print(emoticon)
        
        self?.textView.insertEmoticon(emoticon)
    }
//    override func viewDidLoad() {
//        super.viewDidLoad()
//        view.backgroundColor = UIColor.whiteColor()
//        // Do any additional setup after loading the view.
//    }
//
//    override func didReceiveMemoryWarning() {
//        super.didReceiveMemoryWarning()
//        // Dispose of any resources that can be recreated.
//    }
//   
    override func viewDidAppear(animated: Bool) {
       textView.becomeFirstResponder()
    }
    func inputEmoticon(){
        // MARK: - 指定inputView
        // 取消键盘监听事件
        removeKeyBoardObserver()
        // 取消键盘相应
        textView.resignFirstResponder()
        // 设置输入视图
        textView.inputView = (textView.inputView == nil) ? emoticonVC.view : nil
        // 重新添加键盘监听
        addKeyBoardObserver()
        // 添加键盘响应
        textView.becomeFirstResponder()
    }
    
    override func loadView() {
        view = UIView()
        view.backgroundColor = UIColor.whiteColor()
        prepareNavItems()
        prepareToolBar()
        prepareTextView()
        
        addKeyBoardObserver()
        
    }
    // 添加键盘监听 && 移除键盘监听
    func addKeyBoardObserver(){
        // 添加键盘监听
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardFrameChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
        // 移除键盘监听
    func removeKeyBoardObserver(){
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    func  keyboardFrameChange(notification: NSNotification){
        let rect = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        
        let bottonCons = rect.origin.y
        
        
        let aniDuration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
    
        toolBarBottomCons?.constant = -(UIScreen.mainScreen().bounds.height - bottonCons)
        UIView.animateWithDuration(aniDuration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    deinit{
        removeKeyBoardObserver()
    }
    // 准备文本输入视图
    private func prepareTextView(){
        view.addSubview(textView)
        textView.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0)
        // 设置布局
        textView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: view, size: nil)
        textView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolbar, size: nil)
        textView.alwaysBounceVertical = true
        

        // 添加占位字符
        placeHolder.text = "分享新鲜事。。。"
        placeHolder.sizeToFit()
        textView.addSubview(placeHolder)
        placeHolder.ff_AlignInner(type: ff_AlignType.TopLeft, referView: textView, size:nil,offset:CGPoint(x: 6, y: 6))
    }

    
    // 准备ToolBar
        // 记录toolBar底部约束
    var toolBarBottomCons: NSLayoutConstraint?
    
    
    private func prepareToolBar(){
        view.addSubview(toolbar)
        toolbar.backgroundColor = UIColor(white: 0.75, alpha: 1)
        
        let cons =  toolbar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 44))
        
        toolBarBottomCons = toolbar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        
        // 添加按钮
        let itemSettings = [["imageName": "compose_toolbar_picture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        var items = [UIBarButtonItem]()
        for dict in itemSettings{
            /// 遍历构造函数
            let item = UIBarButtonItem(imgName: dict["imageName"], target: self, action: dict["action"])
            items.append(item)
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        // 移除最后的”弹簧“
        items.removeLast()
        toolbar.items = items
        
    }
    // 准备导航栏
    private func prepareNavItems(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancel")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
    
        navigationItem.rightBarButtonItem?.enabled = false
        
        // 设置title
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 34))
        let title = UILabel(color: UIColor.lightGrayColor(), fontSize: 15)
        title.text = "发布微博"
        titleView.addSubview(title)
        
        let user = UILabel(color: UIColor.lightGrayColor(), fontSize: 14)
        user.text = "SuperIdiot"
        titleView.addSubview(user)
    
        // 设置布局
        title.ff_AlignInner(type: ff_AlignType.TopCenter, referView: titleView, size: nil)
        user.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: titleView, size: nil)
        
        title.sizeToFit()
        user.sizeToFit()
        
        
        navigationItem.titleView = titleView
    }
    
    // 取消和发送
     func cancel(){
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
     func sendStatus(){
        print("send")
    }

    // MARK: -懒加载
    private lazy var textView: UITextView = {
        let textView = UITextView()
        textView.font = UIFont.systemFontOfSize(18)
        textView.backgroundColor  = UIColor.orangeColor()
        // 拖拽键盘推出
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        

        return textView
    }()
    private lazy var toolbar = UIToolbar()
    
    private lazy var placeHolder = UILabel(color: UIColor.lightGrayColor(), fontSize: 18)
}
